package com.ht.shortlink.admin.common.biz.user;

import cn.hutool.json.JSONUtil;
import com.ht.shortlink.admin.common.convention.exception.ClientException;
import com.ht.shortlink.admin.common.convention.result.Results;
import com.ht.shortlink.admin.config.UserFlowRiskControlConfiguration;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Optional;

/**
 * 用户操作流量风控过滤器
 */
@Slf4j
@RequiredArgsConstructor
public class UserFlowRiskControlFilter implements Filter {
    private final StringRedisTemplate stringRedisTemplate;
    private final UserFlowRiskControlConfiguration userFlowRiskControlConfiguration;
    private static final String userFlowRiskControlLua = "lua/user_flow_risk_control.lua";
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(userFlowRiskControlLua)));
        redisScript.setResultType(Long.class);
        String username = Optional.ofNullable(UserContext.getUsername()).map(Object::toString).orElse("other");
        Long result = null;
        try {
            result = stringRedisTemplate.execute(redisScript, Collections.singletonList(username), userFlowRiskControlConfiguration.getTimeWindow().toString());
        }catch (Throwable ex){
            log.error("用户流量风控lua脚本执行错误", ex);
            returnJson((HttpServletResponse) servletResponse, JSONUtil.toJsonStr(Results.failure(new ClientException("系统繁忙， 请稍后再试"))));
        }
        if(result == null || result > userFlowRiskControlConfiguration.getMaxAccessCount()){
            returnJson((HttpServletResponse) servletResponse, JSONUtil.toJsonStr(Results.failure(new ClientException("系统繁忙， 请稍后再试"))));
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        }
    }
}
